<?php

namespace Chat\Service;

use Zend\EventManager\EventManagerInterface;
use Zend\EventManager\ListenerAggregateInterface;
use Zend\EventManager\EventManagerAwareInterface;
use Zend\Db\Adapter\Adapter;
use Chat\Model\ChatTable as ChatTable;
use Chat\Model\UserTable as UserTable;
use Chat\Model\Entity\ChatMessage as ChatMessage;
use Zend\EventManager\StaticEventManager;

class ChatService implements EventManagerAwareInterface, ListenerAggregateInterface
{
	protected $listeners = array();
	
	protected $eventManager;
	
	protected $chatTable;
	
	protected $userTable;
	
	public function __construct(Adapter $adapter) {
		$this->chatTable = new ChatTable($adapter);
		$this->userTable = new UserTable($adapter);
	}
	
public function attach(EventManagerInterface $events)
    {
        $this->listeners[] = $events->attach('newChatMessage', array($this, 'onNewChatMessage'));
    }
    
    public function detach(EventManagerInterface $events)
    {
    	foreach ($this->listeners as $index => $listener) {
    		if ($events->detach($listener)) {
    			unset($this->listeners[$index]);
    		}
    	}
    }
	 
	public function getAllUsersButMe($myID){
		return $this->userTable->getAllUsersButMe($myID);
	}
	
	
	// constructor opens database connection
	public function sendChatMessage($text,$senderID,$receiverID)
	{
		//ONLY write the new message to db 
		$this->chatTable->saveChatMessage(new ChatMessage(array(
				'text' => $text,
				'senderID' => $senderID, 
				'receiverID' => $receiverID
				)
			)
		);
		//notify all listeners about the new message to update the view with the new db informationen 
	//$this->getEventManager()->trigger('sendChatMessage',null,
		//	 array('message' => $text, 'senderID' => $senderID, 'receiverID' =>$receiverID));
	}
	
	public function retrieveAllChatMessages($userID,$myID){
		$result = $this->chatTable->getMessagesBetweenUsers($userID,$myID);
		return $result;
	}
	
	public function retrieveNewChatMessage($senderID,$receiverID,$lastMsgID){
		set_time_limit (600);
		$sendID = $senderID;
		$receiID = $receiverID;
		$msgID = $lastMsgID;
		$secCount = 0;
		\FB::info('Retrieving new messages');
		
		
		/* do {	
			usleep(5000);
			$result = $this->chatTable->fetchLatestMsgBetweenUsers($sendID,$receiID);
		 }while(key($result) == $msgID);*/
		
		$result = $this->chatTable->fetchLatestMsgBetweenUsers($sendID,$receiID);
		//\FB::info('fetchLatestMsgBetweenUsers new:'. key($result).' old:'.$msgID);
	
		if($result == null){
			flush();
			gc_collect_cycles();
			return false;
		}else{
			flush();
			gc_collect_cycles();
			return $result;
		}
				
			
		
			
		
		
		
		
		
		
		//$result = $this->chatTable->fetchLatestMsgBetweenUsers($sendID,$receiID);
		
		
		//\FB::info('fetchLatestMsgBetweenUsers new:'. key($result).' old:'.$msgID);
		//if (key($result) == $msgID){
		//	return false;
		//}else{
		//	return $result;
		//}
		
		
	}
	
	public function lastChatMessageFromUser($senderID,$receiverID){
		
		$result = $this->chatTable->getLastMessageID($senderID,$receiverID);
		return $result;
	}
	
	

	public function setEventManager(EventManagerInterface $eventManager)
	{
		$eventManager->addIdentifiers(array(
        'Application\Service\ServiceInterface',
        get_called_class()
    ));

    $this->eventManager = $eventManager;
	}

	public function getEventManager()
	{
		return $this->eventManager;
	}
	
	public function getAllMessagesByUser($ID){
		
	}
	
	public function onNewChatMessage($e){
	
		//Update the the view with the latest entry for that user in the db
		//$this->view->headScript()->appendScript("jQuery(function(){alert('$message');});");
		//This requires that you add echo $this->headScript() to your view- or layout-script
		//$view = new Zend\View();
		//$scripts = $view->inlineScript();
		//$scripts->appendScript('alert("new Message")');
		//$e->view->headScript()->appendScript("jQuery(function(){alert('eter');});");
		//$viewRenderer = new Zend\Controller\ActionHelper\ViewRenderer();
		//$viewRenderer->setView($view);
		//var_dump($e->getTarget());
		//return new ViewModel();
		\FB::info('Trigger ChatService has been executed for ' . $e->getParam('receiverID'));
		
	}

}

?>
